<template>
  <div class="page">
    <h2>个体化治疗计划</h2>
    <div class="controls">
      <el-input v-model="q" placeholder="按患者或计划名称搜索" clearable style="flex:1" @clear="onClear" />
      <el-select v-model="filterPriority" placeholder="优先级" style="width:160px">
        <el-option label="全部" :value="''" />
        <el-option label="高" value="高" />
        <el-option label="中" value="中" />
        <el-option label="低" value="低" />
      </el-select>
      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增计划</el-button>
        <el-button @click="() => fileInput.click()">导入CSV</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <div class="muted">说明：为患者基于评估结果制定分层、可量化的治疗目标与干预项（可包含CBT-I、药物、呼吸机、睡眠监测等）。</div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="patient" label="患者" width="160" />
      <el-table-column prop="planName" label="计划名称" width="180" />
      <el-table-column prop="linkedEvaluation" label="关联评估" width="160" />
      <el-table-column prop="priority" label="优先级" width="100" />
      <el-table-column prop="goals" label="目标/里程碑" />
      <el-table-column prop="status" label="状态" width="120" />
      <el-table-column label="操作" width="240">
        <template #default="{ row }">
          <el-button size="small" @click="openModal(row.id)">查看/编辑</el-button>
          <el-button size="small" @click="markDone(row.id)" style="margin-left:8px">标记完成</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.id)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '编辑计划' : '新增计划'" v-model="showModal" width="820px">
      <el-form :model="form" label-width="140px">
        <el-form-item label="患者姓名">
          <el-input v-model="form.patient" />
        </el-form-item>
        <el-form-item label="计划名称">
          <el-input v-model="form.planName" />
        </el-form-item>
        <el-form-item label="关联评估">
          <el-input v-model="form.linkedEvaluation" placeholder="例如：PSQI 2025-10-01" />
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="form.priority" style="width:160px">
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标/里程碑">
          <el-input type="textarea" v-model="form.goals" placeholder="可设置可量化目标，例如：PSQI 减少 > 3 分" />
        </el-form-item>
        <el-form-item label="计划项(干预列表)">
          <el-input type="textarea" v-model="form.interventions" placeholder="例如：睡眠卫生教育；CBT-I 6 次；短期米氮平辅药；行PSG" />
        </el-form-item>
        <el-form-item label="预计完成日期">
          <el-date-picker v-model="form.dueDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" style="width:160px">
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="暂停" value="暂停" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.notes" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

    <input ref="fileInput" type="file" accept=".csv" style="display:none" @change="handleFile" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_DATA = [
  {id:1,patient:'张三',planName:'CBT-I 优化计划',linkedEvaluation:'PSQI 2025-10-01',priority:'高',goals:'8 周内PSQI ≤ 5',interventions:'睡眠卫生；CBT-I 6 次；睡眠日记',dueDate:'2025-12-01',status:'进行中',notes:''},
  {id:2,patient:'李四',planName:'OSA 管理',linkedEvaluation:'PSG 2025-09-20',priority:'高',goals:'夜间AHI < 5 或症状改善',interventions:'给予CPAP，夜间随访与依从性监测',dueDate:'2025-11-01',status:'进行中',notes:'需呼吸科配合'}
];

const data = ref([]);
const q = ref('');
const filterPriority = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ patient:'', planName:'', linkedEvaluation:'', priority:'中', goals:'', interventions:'', dueDate:'', status:'进行中', notes:'' });
const fileInput = ref(null);

onMounted(()=>{ load(); });
function load(){ data.value = JSON.parse(JSON.stringify(DEFAULT_DATA)); }
function saveData(){ /* placeholder */ }

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.patient.toLowerCase().includes(qq) || (d.planName||'').toLowerCase().includes(qq))) return false;
    if(filterPriority.value && d.priority !== filterPriority.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.id); });
function onSelectionChange(rows){ selectedRows.value = rows; }

function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.id===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else { Object.assign(form,{patient:'',planName:'',linkedEvaluation:'',priority:'中',goals:'',interventions:'',dueDate:'',status:'进行中',notes:''}); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.patient || !form.planName){ ElMessage.warning('患者姓名和计划名称为必填项'); return; } if(editingId.value){ const it = data.value.find(x=>x.id===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); } else { const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push(Object.assign({id:nid}, JSON.parse(JSON.stringify(form)))); } saveData(); showModal.value=false; }

function deleteOne(id){ ElMessageBox.confirm('确认删除该计划？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.id!==id); saveData(); ElMessage.success('已删除'); })
  .catch(()=>{});
}

function markDone(id){ const it = data.value.find(x=>x.id===id); if(it){ it.status = '已完成'; saveData(); ElMessage.success('已标记为完成'); } }

function batchDelete(){ const ids = selectedIds.value.slice(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.id)); saveData(); selectedIds.value = []; selectedRows.value = []; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['id','patient','planName','linkedEvaluation','priority','goals','interventions','dueDate','status','notes'], ...data.value.map(d=>[d.id,d.patient,d.planName,d.linkedEvaluation,d.priority,d.goals,d.interventions,d.dueDate,d.status,d.notes]) ]; const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='treatment_plans.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }

function handleFile(e){ const f = e.target.files[0]; if(!f) return; const reader = new FileReader(); reader.onload = function(ev){ try{ const text = ev.target.result; const rows = text.split(/\r?\n/).map(r=>r.trim()).filter(Boolean); if(rows.length<2){ ElMessage.warning('没有有效数据'); return; } const headers = parseCSVLine(rows[0]); const items = rows.slice(1).map(r=>parseCSVLine(r)).map(cols=>{ const obj={}; headers.forEach((h,i)=>obj[h.trim()]=cols[i]||''); return obj; }); items.forEach(it=>{ const id = it.id?parseInt(it.id):null; if(id){ const ex = data.value.find(x=>x.id===id); if(ex){ ex.patient = it.patient||ex.patient; ex.planName = it.planName||ex.planName; ex.linkedEvaluation = it.linkedEvaluation||ex.linkedEvaluation; ex.priority = it.priority||ex.priority; ex.goals = it.goals||ex.goals; ex.interventions = it.interventions||ex.interventions; ex.dueDate = it.dueDate||ex.dueDate; ex.status = it.status||ex.status; ex.notes = it.notes||ex.notes; return; } } const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push({id:nid,patient:it.patient||'未命名',planName:it.planName||'',linkedEvaluation:it.linkedEvaluation||'',priority:it.priority||'中',goals:it.goals||'',interventions:it.interventions||'',dueDate:it.dueDate||'',status:it.status||'进行中',notes:it.notes||''}); }); saveData(); ElMessage.success('导入完成'); }catch(err){ ElMessage.error('导入失败'); }}; reader.readAsText(f,'utf-8'); e.target.value=''; }

function parseCSVLine(line){ const cols=[]; let cur=''; let inQ=false; for(let i=0;i<line.length;i++){ const ch=line[i]; if(inQ){ if(ch==='"'){ if(line[i+1]==='"'){ cur+='"'; i++; }else{ inQ=false; } }else{ cur+=ch; } }else{ if(ch==='"'){ inQ=true; }else if(ch===','){ cols.push(cur); cur=''; }else{ cur+=ch; } } } cols.push(cur); return cols; }
function onClear(){ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>